package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import com.itheima.service.Impl.UserServiceImpl;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @param
 * @return
 */
@WebServlet("/userServlet/*")
public class UserServlet extends BeanServlet {
    ObjectMapper om= new ObjectMapper();
    //创建业务层对象复用
    UserService service=new UserServiceImpl();
    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //调用业务层的查询所有方法
        List<User> list=service.findAll();
        //使用工具类还是插件什么的，先创建该对象，再调用方法将集合转为json类型的字符串写回前端
        String s = om.writeValueAsString(list);
        /*设置响应的字符集主要是确定json类型*/
        resp.setContentType("text/json;charset=UTF-8");
        //写回
        resp.getWriter().write(s);
    }
    protected void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //字符流读取前端发送的json格式的字符串
        BufferedReader reader = req.getReader();
        //将字符串转为json对象
        User user = om.readValue(reader, User.class);
        //调用业务层新增方法
        boolean flag = service.save(user);
        /*设置响应的字符集主要是确定json类型*/
        resp.setContentType("text/json;charset=UTF-8");
        //写回
        resp.getWriter().write(String.valueOf(flag));
    }
    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取页面的请求参数
        String uid = req.getParameter("id");
        //调用业务层查询单个方法
        User user = service.findById(Integer.parseInt(uid));
        String s = om.writeValueAsString(user);
        /*设置响应的字符集主要是确定json类型*/
        resp.setContentType("text/json;charset=UTF-8");
        //写回
        resp.getWriter().write(s);
    }
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //字符流读取前端发送的json格式的字符串
        BufferedReader reader = req.getReader();
        //将字符串转为json对象
        User user = om.readValue(reader, User.class);
        //调用业务层新增方法
        boolean flag = service.update(user);
        /*设置响应的字符集主要是确定json类型*/
        resp.setContentType("text/json;charset=UTF-8");
        //写回
        resp.getWriter().write(String.valueOf(flag));
    }
    protected void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     //获取前端请求参数
        String ids = req.getParameter("ids");
        //调用业务层批量删除方法
        boolean flag = service.deleteByIds(ids);
        /*设置响应的字符集主要是确定json类型*/
        resp.setContentType("text/json;charset=UTF-8");
        //写回
        resp.getWriter().write(String.valueOf(flag));
    }
}
